﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

using Common.IO.FileIO;

namespace BL.ServerBL
{
    public class ServerChannel
    {
        int Port = 9000;
        string ObjectUrl = "RemotingCommon";
        WellKnownObjectMode Mode = WellKnownObjectMode.SingleCall;
        Type RemotingType = typeof(ServerRemotingCommon);
        public ServerChannel(string port)
        {
            this.Port = Convert.ToInt32(port);
        }

        public ServerChannel()
        { 

        }

        public bool RegisterServerChannel()
        {
            try
            {
                TcpServerChannel tcpsc = new TcpServerChannel(Port);
                ChannelServices.RegisterChannel(tcpsc);
                RemotingConfiguration.RegisterWellKnownServiceType(RemotingType,
                    ObjectUrl, Mode);
            }
            catch (System.Net.Sockets.SocketException)
            {
                return false;
            }
            return true;
        }

        public void ServerChannelControl(bool bl)
        {
            if (bl)
            {
                this.RegisterServerChannel();
            }
            else
            {
                this.UnRegisterServerChannel();
            }
        }

        public void UnRegisterServerChannel()
        {
            foreach (IChannel ic in ChannelServices.RegisteredChannels)
            {
                ((TcpServerChannel)ic).StopListening(null);
                ChannelServices.UnregisterChannel(ic);
            }
        }

    }
}
